import { useState, useEffect, useCallback } from "react";
import { Text, TouchableOpacity, DeviceEventEmitter } from "react-native";
import type { EmitterSubscription } from "react-native";
import globalMethods from "@/GlobalMethodProvider";
import { getPermissions } from "@/utils";
import { Module } from "@/utils/nativeModules";

import Btn from "@/components/Btn";

// @ts-ignore
import DialogAndroid from "react-native-dialogs";

// // 标签数据类型
// export type EquipmentDataType = Pick<
//   LogisticsEquipmentType,
//   "epcNum" | "equipmentName" | "equipmentBrand" | "equipmentModel" | "purchaseDate"
// >;

type StateType = {
  /** 二维码原始数据 */
  qrCodeRaw: string;
  /** 读取到的标签数据 */
  // tagData: EquipmentDataType | null;
};

/** 扫码结果事件实例 */
let scanResultLinstener: EmitterSubscription | null = null;

// 二维码扫描
const useScanQrCode = () => {
  const [state, _setState] = useState<StateType>({
    qrCodeRaw: ""
    // tagData: null
  });

  // 通用更新状态单个
  const setState = useCallback((field: keyof typeof state, val: any) => {
    _setState(_state => {
      return { ..._state, [field]: val };
    });
  }, []);

  // 通用更新状态(对象)
  const setObjState = useCallback((obj: Partial<typeof state>) => {
    _setState(_state => {
      return { ..._state, ...obj };
    });
  }, []);

  // 将扫描出来的字符串数据加工成标签数据
  // const buildEpcData = useCallback((rawValue: string) => {
  //   const list = rawValue.split("\r\n");
  //   for (let i = 0; i < list.length; i++) {
  //     const item = list[i];
  //     const [label, value] = item.split(":");
  //     if (value) {
  //       list[i] = value;
  //     } else {
  //       list[i] = "";
  //       console.log("数据切片异常: ", item);
  //     }
  //   }
  //   const epcData: EquipmentDataType = {
  //     epcNum: list[0],
  //     equipmentName: list[1],
  //     equipmentBrand: list[2],
  //     equipmentModel: list[3],
  //     purchaseDate: list[4]
  //   };

  //   return epcData;
  // }, []);

  // 修改标签数据
  const handleScanData = useCallback(async (qrCodeRaw: string) => {
    console.log("qrCodeRaw: ", qrCodeRaw);

    // const epcData = buildEpcData(qrCodeRaw);
    // console.log("解析后的扫码数据: ", epcData);

    // if (epcData.epcNum) {
    //   try {
    //     setObjState({
    //       qrCodeRaw,
    //       tagData: epcData
    //     });
    //   } catch (err) {
    //     console.log("err: ", err);
    //   }
    // } else {
    //   globalMethods.$warning("二维码异常, 没有检测到RFID数据");
    // }
  }, []);

  useEffect(() => {
    getPermissions("android.permission.CAMERA", "相机权限");
    // 扫码事件
    scanResultLinstener = DeviceEventEmitter.addListener(Module.SCAN_RESULT_EVENT_KEY, (msg: any) => {
      const scanData = msg[Module.SCAN_RESULT_DATA_KEY];
      console.log("二维码数据: ", scanData);
      if (scanData) {
        // 处理数据
        handleScanData(scanData);
      }
    });

    return () => {
      if (scanResultLinstener) {
        scanResultLinstener.remove();
        scanResultLinstener = null;
      }
    };
  }, [handleScanData]);

  return {
    ...state,
    gotoScanQrCode: Module.gotoScanQrCode
  };
};

export default useScanQrCode;
